package com.duartepeixinho.P3D.Renderers 
{
	import com.duartepeixinho.P3D.Cameras.Camera;
	import com.duartepeixinho.P3D.Core.Geom.Face3;
	import com.duartepeixinho.P3D.Materials.Materials;
	import com.duartepeixinho.P3D.Scenes.Scene;
	import com.duartepeixinho.P3D.ViewPort.ViewPort;
	import flash.geom.Point;
	
	/**
	 * P3D
	 * @version 0.1
	 * @author Duarte Peixinho
	 */
	public class Renderer extends RendererBase implements IRenderer
	{
		
		public function Renderer() 
		{
			
		}
		
		public function singleRender(scene:Scene, viewport:ViewPort, camera:Camera):void {
			
			// update vertices
			updateTriangles(scene, camera);
			
			// clear
			graphics.clear();
			
			// triangles count
			var tri:uint = 0;
			
			for (var i:uint = 0; i < faces.length; i++) {
				var f:Face3 = faces[i];
				if (renderTriangle(f, vertices, f.material, viewport)) tri++;
			}
			scene.triangles = faces.length;
			scene.drawedTriangles = tri;
		}
		
		private function renderTriangle(tri:Face3, points:Array, material:Materials, viewport:ViewPort):Boolean
		{	
			var A:Point = new Point(viewport.convert3Dto2D(points[tri.a]).x, viewport.convert3Dto2D(points[tri.a]).y);
			var B:Point = new Point(viewport.convert3Dto2D(points[tri.b]).x, viewport.convert3Dto2D(points[tri.b]).y);
			var C:Point = new Point(viewport.convert3Dto2D(points[tri.c]).x, viewport.convert3Dto2D(points[tri.c]).y);
			
			if (!triangleIsBackFace(A, B, C) || material.doubleSided) {
				
				material.drawTriangle(tri, A, B, C, this.graphics);
				
				return true;				
			}
			
			return false;
		}
		
	}	

}